import 'dart:convert';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:encrypt_and_decrypt_files/dio_util.dart';
import 'package:encrypt_and_decrypt_files/encrypt_page/encrypt_decrypt_page.dart';
import 'package:encrypt_and_decrypt_files/history_list/history_detail.dart';
import 'package:encrypt_and_decrypt_files/widget/extension.dart';
import 'package:encrypt_and_decrypt_files/widget/theme_provider.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';

class HistoryListPage extends StatefulWidget {
  const HistoryListPage({super.key});

  @override
  // ignore: library_private_types_in_public_api
  _HistoryListPageState createState() => _HistoryListPageState();
}

class _HistoryListPageState extends State<HistoryListPage>
    with SingleTickerProviderStateMixin {
  List<RecordProcessingModel> _records = [];

  void refreshData() {}

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _loadHistoryList();
    });
  }

  @override
  Widget build(BuildContext context) {
    final themeProvider = Provider.of<ThemeProvider>(context);

    return Scaffold(
      appBar: AppBar(
        title: Text('History List'.t(context)),
        backgroundColor: themeProvider.mainColor,
        centerTitle: true,
      ),
      body: EasyRefresh(
        onRefresh: () {
          refreshData();
        },
        child: ListView(
            children: List.generate(_records.length, (index) {
          return _buildEveryItem(_records[index]);
        })),
      ),
    );
  }

  Widget _buildEveryItem(RecordProcessingModel model) {
    return Container(
      padding: const EdgeInsets.all(16),
      margin: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
      ),
      child: Column(children: [
        Row(
          children: [
            Text('${'type'.t(context)}: ${model.type}'),
            const SizedBox(width: 16),
            Text('${'algorithm'.t(context)}: ${model.algorithm}'),
          ],
        ),
        const SizedBox(height: 16),
        Text('${'originFile'.t(context)}: ${model.originFile}'),
        const SizedBox(width: 16),
        Text('${'destFile'.t(context)}: ${model.destFile}'),
        const SizedBox(height: 16),
        Container(
          padding: const EdgeInsets.only(left: 30, right: 30),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              TextButton(
                  onPressed: () {
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (_) => HistoryDetailPage(
                                  detailModel: model,
                                )));
                  },
                  child: Text('View'.t(context))),
              TextButton(
                  onPressed: () {
                    _deleteHistory(model.id!);
                  },
                  child: Text('Delete'.t(context))),
            ],
          ),
        ),
      ]),
    );
  }

  Future<void> _loadHistoryList({bool isNeedShowMsg = true}) async {
    const url = '/get_processing_history';
    String token = SpUtil.getString('token') ?? '';

    var response = await DioHttp.of(context).get(url, null, token);
    var resString = json.decode(response.toString());
    if (isNeedShowMsg) {
      Fluttertoast.showToast(msg: resString['msg']);
    }
    if (resString['code'] == 200) {
      if (resString['data'] != null) {
        _records = resString['data']
            .map<RecordProcessingModel>(
                (item) => RecordProcessingModel.fromJson(item))
            .toList();
      } else {
        _records = [];
      }
      setState(() {});
    }
  }

  Future<void> _deleteHistory(int id) async {
    const url = '/delete_history';
    String token = SpUtil.getString('token') ?? '';
    Map<String, dynamic> params = {'history_id': id};

    var response = await DioHttp.of(context).post(url, params, token);
    var resString = json.decode(response.toString());
    Fluttertoast.showToast(msg: resString['msg']);
    if (resString['code'] == 200) {
      _loadHistoryList(isNeedShowMsg: false);
    }
  }
}
